import React, { useRef, useState, useEffect } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Space, Table, Input, Switch, Divider, Tree, Spin } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { userpage, userpagedelete, updateUserStatus, getUserDepartmentInfo,getAssignTree, getUserAssignedData ,putAssign, getAllowAssignTree} from '@/services/system/user';
import { useNavigate } from 'react-router-dom';
import AuthorizedButton from '@/components/AuthorizedButton';
console.log('AuthorizedButton:', AuthorizedButton);

import { useOutletContext } from '@umijs/max';
import { log } from '@antv/g2plot/lib/utils';
import type { DataNode } from 'antd/es/tree';

interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}

interface TreeNodeType {
  children?: TreeNodeType[];
  deptId: string;
  name: string;
  positions: Array<{
    id: string;
    name: string;
    // 其他岗位相关字段
  }>;
  type: 'department';
}

const UserManage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [Userrecords, setUserrecords] = useState<any[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  console.log('buttonData:', buttonData);

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState(''); // 用于存储搜索框输入的文本
  const navigate = useNavigate();
  const [isDepartmentModalVisible, setIsDepartmentModalVisible] = useState(false);
  const [departmentInfo, setDepartmentInfo] = useState<any>(null);
  const [isAssignModalVisible, setIsAssignModalVisible] = useState(false);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [currentRecord, setCurrentRecord] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [institutionId, setInstitutionId] = useState<string>('');

  useEffect(() => {
    // 直接从localStorage获取institutionId
    const storedInstitutionId = localStorage.getItem('institutionId');
    console.log('storedInstitutionId:', storedInstitutionId);
    if (storedInstitutionId) {
      setInstitutionId(storedInstitutionId);
      fetchData({ institutionId: storedInstitutionId });
    }
  }, []);

  // 添加一个监听institutionId变化的useEffect
  useEffect(() => {
    if (institutionId) {
      fetchData({ institutionId });
    }
  }, [institutionId]);

  const fetchData = async (params = {}) => {
    try {
      const response = await userpage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        ...params
      });

      if (response.code === 200) {
        console.log('response.data.records>',response.data);

        let filteredData = response.data;
        console.log('filteredData>',filteredData);

        if (searchText) {
          filteredData = filteredData.filter(record => record.userName.includes(searchText));
        }
console.log('filteredData...',filteredData);

        setUserrecords(filteredData);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  const columns: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render: (value) => (value === 0 ? '男' : '女'),
    },
    {
      title: '地址',
      dataIndex: 'address',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.status == 0}
          onChange={(checked) => handleStatusChange(record.id, checked)}
        />
      ),
    },

    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => (
        <span>
          <Space split={<Divider type="vertical" />}>
            <AuthorizedButton
              buttonData={buttonData}
              action="edit"
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              编辑
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="delete"
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
                // backgroundColor:'red'
              }}
            >
              删除
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="view"
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              详情
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="allow"
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleAllow(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              分配
            </AuthorizedButton>
          </Space>
        </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/usermanage/add');
  };

  const handleEdit = (record) => {
    navigate('/system/usermanage/edit', { state: { record } });
  };

  const handleDelete = (record) => {
    console.log('record:', record);
    const response = userpagedelete({
      userId: record.userId, // 确保record.id是一个数字或字符串
      institutionId: record?.institutionId
    });
    return response.then(res => {
      if (res.code === 200) {
        message.success('删除成功');
        fetchData();
      }
      // 这里可以处理其他逻辑，比如失败情况
    }).catch(error => {
      console.error('删除失败:', error);
      // 这里可以处理错误情况
    });
  };

  const handleView = (record: any) => {
    navigate('/system/usermanage/view', { state: { record } });
  };



  const handleStatusChange = async (userId: string, checked: boolean) => {
    try {
      const response = await updateUserStatus({
        id: userId,
        status: checked ? 0 : 1
      });

      if (response.code === 200) {
        message.success('状态更新成功');
        fetchData(); // 刷新表格数据
      } else {
        message.error(response.msg || '状态更新失败');
        // 如果失败，刷新数据以恢复原状态
        fetchData();
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
      // 如果出错，刷新数据以恢复原状态
      fetchData();
    }
  };


  const handleAssignOk = async () => {
    try {
      setLoading(true);

      const deptMap = new Map();
      console.log('selectedKeys:', selectedKeys);

      selectedKeys.forEach(key => {
        const keyStr = key.toString();
        if (keyStr.startsWith('position-')) {
          // 从position key中提取部门ID和岗位ID
          const [_, deptId, id] = keyStr.split('-');
          console.log('deptId:', deptId);
          console.log('id:', id);
          if (!deptMap.has(deptId)) {
            deptMap.set(deptId, { deptId, positionIds: [] });
          }
          // 确保只添加 id 部分
          const positionId = id.split('_')[0]; // 如果有其他后缀，去掉
          deptMap.get(deptId).positionIds.push(positionId);
        }
      });

      // 过滤掉没有岗位的部门，并确保 ID 格式正确
      const assignData = Array.from(deptMap.values())
        .filter(item => item.positionIds.length > 0)
        .map(item => ({
          deptId: item.deptId,
          positionIds: item.positionIds.map(id => id) // 确保 ID 格式正确
        }));

      console.log('assignData:', assignData);

      if (assignData.length === 0) {
        message.warning('请至少选择一个岗位');
        return;
      }

      const response = await putAssign(assignData);

      if (response.code === 200) {
        message.success('分配成功');
        setIsAssignModalVisible(false);
        setSelectedKeys([]);
        setCurrentRecord(null);
        // 刷新列表
        fetchData();
      } else {
        message.error(response.msg || '分配失败');
      }
    } catch (error) {
      console.error('分配失败:', error);
      message.error('分配失败');
    } finally {
      setLoading(false);
    }
  };

  // 添加搜索处理函数
  const handleSearch = (value: string) => {
    setSearchText(value);
    fetchData({ institutionId, userName: value });
  };

  return (
    <div style={{ background: '#f0f2f5', minHeight: '100vh' }}>
      <PageContainer
        style={{
          background: '#fff',
          borderRadius: '8px',
          padding: '24px',
          margin: '24px'
        }}
      >
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16
        }}>
          <AuthorizedButton
            buttonData={buttonData}
            action="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </AuthorizedButton>
          <div style={{ width: '300px' }}>
            <Input
              placeholder="请输入用户名进行搜索"
              value={searchText}
              onChange={e => handleSearch(e.target.value)}
              suffix={<SearchOutlined style={{ color: '#1890ff' }} />}
              style={{
                borderRadius: '20px',
                backgroundColor: '#f5f5f5',
                border: 'none',
                padding: '8px 16px'
              }}
            />
          </div>
        </div>
        <Table
          columns={columns}
          dataSource={Userrecords}
          pagination={{
           ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchData({ current: page, size: pageSize });
            },
          }}
        />
      </PageContainer>
      <Modal
        title="部门及岗位信息"
        open={isDepartmentModalVisible}
        onCancel={() => setIsDepartmentModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDepartmentModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {departmentInfo && (
          <div>
            {departmentInfo.map((item: any, index: number) => (
              <div key={item.deptId} style={{ marginBottom: index !== departmentInfo.length - 1 ? '20px' : 0 }}>
                <p style={{ fontWeight: 'bold', marginBottom: '8px' }}>
                  部门名称：{item.deptName}
                </p>
                <div style={{ marginLeft: '20px' }}>
                  <p style={{ marginBottom: '4px' }}>岗位列表：</p>
                  {item.positionsName.map((position: string, pIndex: number) => (
                    <p
                      key={position}
                      style={{
                        marginLeft: '20px',
                        marginBottom: '4px',
                        color: '#666'
                      }}
                    >
                      • {position}
                    </p>
                  ))}
                </div>
                {index !== departmentInfo.length - 1 && (
                  <div style={{ borderBottom: '1px solid #f0f0f0', margin: '12px 0' }} />
                )}
              </div>
            ))}
          </div>
        )}
      </Modal>
      <Modal
        title="分配部门岗位"
        open={isAssignModalVisible}
        onOk={handleAssignOk}
        onCancel={() => {
          setIsAssignModalVisible(false);
          setSelectedKeys([]);
          setCurrentRecord(null);
        }}
        width={600}
        confirmLoading={loading}
      >
        {/* console.log('treeData:', treeData); */}

        {treeData.length > 0 ? (
          // console.log('treeData:', treeData);
          <Tree
            checkable
            checkedKeys={selectedKeys}
            onCheck={(checked, info) => {
              console.log('checked info:', info);
              setSelectedKeys(checked as string[]);
            }}
            treeData={treeData}
            defaultExpandAll
            height={400}
            style={{ maxHeight: '60vh', overflow: 'auto' }}
            titleRender={(nodeData: any) => (
              <span style={{
                color: nodeData.type === 'department' ? '#1890ff' : 'inherit',
                fontWeight: nodeData.type === 'department' ? 500 : 'normal'
              }}>
                {nodeData.title}
              </span>
            )}
          />
        ) : (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <Spin tip="加载中..." />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default UserManage;
